﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using DevExpress.XtraEditors;

namespace Mota.XMLControls
{
    public class MyDxCheckedListBox:CheckedListBoxControl
    {
        public event PropertyChangedEventHandler ItemsChanged;
        public MyDxCheckedListBox():base()
        {
            this.ItemCheck += MyDxCheckedListBox_ItemCheck;
        }

        void MyDxCheckedListBox_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (this.DataSource != null)
            {
                this.OnItemsChanged(null);
            }
        }
        public IEnumerable<KeyValuePair<string,bool>> GetItemsStates()
        {
            var i = 0;
            var item = this.GetItem(i) as DataRowView;
            while (item != null)
            {
                yield return new KeyValuePair<string, bool>(this.GetItemValue(i).ToString(),
                                                                this.GetItemChecked(i));

                item = this.GetItem(++i) as DataRowView;
            }
        }
        //Makes this property bindable.
        [Bindable(true)]
        public string XmlItems
        {
            get
            {

                XElement items = new XElement("Items",
                        GetItemsStates().Select(el=>new XElement("Item",
                            new XAttribute("Value",el.Key)){Value = el.Value.ToString().ToLower()})
                    );
                return items.ToString();
            }
            set
            {

                this.UnCheckAll();
                if (!String.IsNullOrEmpty(value))
                {
                    XElement items = XElement.Parse(value);
                    Dictionary<string,bool> xmlItems = items.Elements("Item").ToDictionary(key => key.Attribute("Value").Value,
                                                        val => Convert.ToBoolean(val.Value));

                    var i = 0;
                    DataRowView item = this.GetItem(i) as DataRowView;
                    while (item != null)
                    {
                        if (xmlItems[item[this.ValueMember].ToString()])
                            this.SetItemChecked(i, true);
                        else
                            this.SetItemChecked(i, false);

                        item = this.GetItem(++i) as DataRowView;
                    }
                }
            }
        }
        public void OnItemsChanged(PropertyChangedEventArgs e)
        {
            //Raise the event
            if (ItemsChanged != null)
                ItemsChanged(this, e);
        }
    }
}
